package com.movie.controller;

import com.movie.dto.UserDTO;
import com.movie.entity.User;
import com.movie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员用户管理控制器
 */
@RestController
@RequestMapping("/api/admin/users")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
@PreAuthorize("hasRole('ADMIN')")
public class AdminUserController {

    @Autowired
    private UserService userService;

    /**
     * 分页获取用户列表
     * @param page 页码（从1开始）
     * @param size 每页大小
     * @param keyword 搜索关键字（可选）
     * @return 分页用户数据
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword) {
        
        try {
            List<User> users;
            int total;
            
            if (keyword != null && !keyword.trim().isEmpty()) {
                // 搜索用户
                users = userService.searchUsers(keyword.trim(), page, size);
                total = userService.getSearchUserCount(keyword.trim());
            } else {
                // 获取所有用户
                users = userService.getUsersPaged(page, size);
                total = userService.getUserCount();
            }
            
            // 转换为DTO，隐藏敏感信息
            List<UserDTO> userDTOs = new ArrayList<>();
            for (User user : users) {
                UserDTO dto = new UserDTO();
                dto.setId(user.getId());
                dto.setUsername(user.getUsername());
                dto.setEmail(user.getEmail());
                dto.setPhone(user.getPhone());
                dto.setAddress(user.getAddress());
                dto.setBalance(user.getBalance());
                dto.setRegisterTime(user.getRegisterTime());
                userDTOs.add(dto);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", userDTOs);
            response.put("totalElements", total);
            response.put("totalPages", (int) Math.ceil((double) total / size));
            response.put("currentPage", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取用户列表失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 根据ID获取用户详情
     * @param id 用户ID
     * @return 用户详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<UserDTO> getUserById(@PathVariable Long id) {
        try {
            User user = userService.getUserById(id);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }
            
            UserDTO dto = new UserDTO();
            dto.setId(user.getId());
            dto.setUsername(user.getUsername());
            dto.setEmail(user.getEmail());
            dto.setPhone(user.getPhone());
            dto.setAddress(user.getAddress());
            dto.setBalance(user.getBalance());
            dto.setRegisterTime(user.getRegisterTime());
            
            return ResponseEntity.ok(dto);
            
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 获取用户统计信息
     * @return 用户统计数据
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getUserStats() {
        try {
            int totalUsers = userService.getUserCount();
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalUsers", totalUsers);
            
            return ResponseEntity.ok(stats);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取用户统计失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
}
